﻿using DICOMViewer.Config;
using DICOMViewer.Utility;
using Leadtools.DicomDemos.Scu.CEcho;
using Leadtools.DicomDemos.Scu.CFind;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Leadtools.Dicom;

namespace DICOMViewer.UC
{
    public partial class ServerSettingEditForm : Form
    {
        public ServerSettingEditForm()
        {
            InitializeComponent();
        }

        private ServerInfo serverInfo;
        private List<ServerInfo> serverList;
        private CEcho cecho;

        public ServerSettingEditForm(ServerInfo serverInfo, List<ServerInfo> serverList) : this(serverList)
        {
            this.serverInfo = serverInfo;
            this.tbxAeTitle.Text = serverInfo.AETitle;
            this.tbxIP.Text = serverInfo.Ip;
            this.tbxPort.Text = serverInfo.Port.ToString();
        }
        public ServerSettingEditForm(List<ServerInfo> serverList) :this()
        {
            this.serverList = serverList;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            System.Net.IPAddress ipAddress ;
            bool ipValid = System.Net.IPAddress.TryParse(tbxIP.Text.Trim(), out ipAddress);
            if (!ipValid)
            {
                MessageBox.Show("IP地址不合法！请重新输入！");
                return;
            }
            int portVal;
            bool portValid = int.TryParse(tbxPort.Text, out portVal);
            if (!portValid)
            {
                MessageBox.Show("端口号不合法！请重新输入！");
                return;
            }
            if (serverInfo != null)
            {
                if (serverInfo.Ip!= this.tbxIP.Text.Trim() &&
                    serverList.Any(o => o.Ip == this.tbxIP.Text.Trim()))
                {
                    MessageBox.Show("该IP已在列表中！请重新输入！");
                    return;
                }
                serverInfo.AETitle = this.tbxAeTitle.Text.Trim();
                serverInfo.Ip = this.tbxIP.Text.Trim();
                serverInfo.Port = int.Parse(this.tbxPort.Text.Trim());
                this.DialogResult = DialogResult.OK;
                return;
            }
            else
            {
                if (serverList.Any(o => o.Ip == this.tbxIP.Text.Trim()))
                {
                    MessageBox.Show("该IP已在列表中！请重新输入！");
                    return;
                }
                serverList.Add(new ServerInfo()
                {
                    AETitle = this.tbxAeTitle.Text.Trim(),
                    Ip = this.tbxIP.Text.Trim(),
                    Port = int.Parse(this.tbxPort.Text.Trim())
                });
                this.DialogResult = DialogResult.OK;
                return;
            }
        }

        private void btnTest_Click(object sender, EventArgs e)
        {
            cecho = new CEcho()
            {
                ImplementationClass = ConstDefineValues.CONFIGURATION_IMPLEMENTATIONCLASS,
                ProtocolVersion = ConstDefineValues.CONFIGURATION_PROTOCOLVERSION,
                ImplementationVersionName = ConstDefineValues.CONFIGURATION_IMPLEMENTATIONVERSIONNAME
            };
            cecho.Status += Cecho_Status;
            cecho.Echo(new Leadtools.DicomDemos.DicomServer()
            {
                AETitle = this.tbxAeTitle.Text.Trim(),
                Address = System.Net.IPAddress.Parse(this.tbxIP.Text.Trim()),
                Port = int.Parse(this.tbxPort.Text.Trim()),
                Timeout =30,
                IpType = DicomNetIpTypeFlags.Ipv4
            }, Utility.ComSettingReader.getClientConfig().AETitle);
            this.Enabled = false;
            this.Cursor = Cursors.WaitCursor;
        }

        private void Cecho_Status(object sender, Leadtools.DicomDemos.StatusEventArgs e)
        {Console.WriteLine(string.Format("{0}  :  ResultType = {1}  ||  Error = {2}  || Source = {3}",DateTime.Now, e.Type, e.Error,e.Source));
            if (e.Error != DicomExceptionCode.Success)
            {
                MessageBox.Show(string.Format("连接失败！请求返回状态为{0}，失败原因为{1}。", e.Type, e.Error));
                this.Enabled = true;
                this.Cursor = Cursors.Default;
                return;
            }
            else
            {
                if (e.Type == Leadtools.DicomDemos.StatusType.ReceiveAssociateReject)
                {
                    MessageBox.Show(string.Format("连接失败！请求返回状态为{0}。", e.Type));
                    this.Enabled = true;
                    this.Cursor = Cursors.Default;
                    return;
                }
                if (e.Type == Leadtools.DicomDemos.StatusType.ReceiveReleaseResponse)
                {
                    MessageBox.Show("连接成功！");
                    this.Enabled = true;
                    this.Cursor = Cursors.Default;
                    return;
                }
                if (e.Type == Leadtools.DicomDemos.StatusType.Timeout)
                {
                    MessageBox.Show("连接超时，请重试！");
                    this.Enabled = true;
                    this.Cursor = Cursors.Default;
                    return;
                }
                if (e.Type == Leadtools.DicomDemos.StatusType.Error)
                {
                    MessageBox.Show("Dicom error！Because of PresentationID=0 or DicomAssociateAccept error!Please retry later!");
                    this.Enabled = true;
                    this.Cursor = Cursors.Default;
                    return;
                }

            }


        }

        private void ServerSettingEditForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (cecho != null)
            {
                cecho.Terminate();
                cecho.CloseForced(true);
            }

        }
    }
}